﻿using Devonline.Identity;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace ProjectManagement.Controllers;

[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class UsersController : ControllerBase
{
    private readonly IDataWithAttachmentService<IdentityDbContext, User> _dataService;

    public UsersController(IDataWithAttachmentService<IdentityDbContext, User> dataService)
    {
        _dataService = dataService;
    }

    [HttpGet]
    public async Task<IActionResult> GetAsync()
    {
        var users = await _dataService.GetQueryable().ToListAsync();
        if (users.IsNotNullOrEmpty())
        {
            users.ForEach(x => x.PasswordHash = null);
        }

        return Ok(users);
    }

    /// <summary>
    /// 用户新增使用默认密码
    /// </summary>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] User entitySet) => Ok(await _dataService.AddAsync(entitySet));

    /// <summary>
    /// 用户修改忽略密码字段
    /// </summary>
    /// <param name="key"></param>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<IActionResult> Put([FromBody] User entitySet) => Ok(await _dataService.UpdateAsync(entitySet));

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        await _dataService.DeleteAsync(id);
        return Ok();
    }
}
